package com.uglygeeker.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.uglygeeker.common.mybatis.BaseServiceImpl;
import com.uglygeeker.entity.Area;
import com.uglygeeker.mapper.AreaMapper;
import com.uglygeeker.service.IAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * Created by tanxw on 2016/12/9.
 */
@Service
public class AreaServiceImpl extends BaseServiceImpl<Area> implements IAreaService {

    @Autowired
    private AreaMapper areaMapper;

    @Override
    public Mapper<Area> getMapper() {
        return super.getMapper();
    }

    @Override
    @Cacheable(value ="common",unless = "#result == null")
    public List<Area> getAreaList(){

        List<Area> sourceList =  areaMapper.getAreaList();
        Area area = new Area();
        area.setSonAreaList(Lists.<Area>newArrayList());
        area.setCode(null);
        return sourceList(sourceList,area).getSonAreaList();
    }

    @Override
    public PageInfo<Area> getAreaByPage(int pageNum, int pageSize){
        PageHelper.startPage(pageNum, pageSize, true);
        Example example = new Example(Area.class);
        example.selectProperties("id,name,code,type,parentCode");
        return selectByPage(example);
    }

    private Area sourceList(List<Area>sourceList,Area area){
        for (Area sonArea :sourceList){
            if(sonArea.getParentCode() == area.getCode()){
                area.getSonAreaList().add(sourceList(sourceList,sonArea));
            }
        }
        return area;
    }
}
